package com.kkb.demo.netty.example.asyncmode;

/**
 * 实现一个简单带回调的异步任务
 */
public class Bootstrap {
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();

        Worker worker = bootstrap.newWorker();

        Wrapper wrapper = new Wrapper();
        wrapper.setWorker(worker);
        wrapper.setParam("hello");

        bootstrap.doWork(wrapper).addListener(new Listener() {
            @Override
            public void result(Object result) {
                System.out.println("result:"+result+",listener thread:"+Thread.currentThread().getName());
            }
        });

        System.out.println("strap thread:"+Thread.currentThread().getName());

    }

    private Wrapper doWork(Wrapper wrapper) {
        new Thread(() -> {
            Worker worker = wrapper.getWorker();
            System.out.println("work param:"+wrapper.getParam()+",thread:"+Thread.currentThread().getName());
            String result = worker.action(wrapper.getParam());

            if( wrapper.getListener()==null){

            }
            wrapper.getListener().result(result);
        }).start();

        return wrapper;
    }

    private Worker newWorker() {
        return new Worker() {
            @Override
            public String action(Object object) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return object + " world";
            }
        };
    }
}
